package diamondServer.clientserver.threadpool;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

import diamondServer.clientserver.BufferFactory;

public class ClientTask extends Task {
	
	private int sendingTimes = 1;	// # of times the string is sent
	private long delay = 0;// delay between sends
	private long startTime = 0;
	private InetSocketAddress inAddress;
	
	public ClientTask(String msg,InetSocketAddress address) {
		super(msg);
		this.inAddress = address;
		// TODO Auto-generated constructor stub
	}
	
	public ClientTask(String msg, InetSocketAddress address ,int sendingTimes, long delay, long startTime) {
		super(msg);
		this.sendingTimes = sendingTimes;
		this.delay = delay;
		this.startTime = startTime;
		this.inAddress = address;
	}


	@Override
	public void toDo()  {
		System.out.println("Client Thread: " + Thread.currentThread().getName() + " Message = " + this.message);
		SocketChannel sc = null;
		try {
			Thread.sleep(this.startTime);
		} catch (InterruptedException e2) {e2.printStackTrace();}
		
		for (int i = 0; i < this.sendingTimes; i++)
		{
			// each iteration sends a single message (creates a channel+buffer and sends the message)
			try {
				Thread.sleep(this.delay);
				sc = InitChannel();
				sc.write(new BufferFactory(this.message).getByteBuffer());
				sc.close();
			} catch (InterruptedException e1) {e1.printStackTrace();
			} catch (IOException e) {e.printStackTrace();}
			
		}
		
	}

	
	
	public SocketChannel InitChannel() throws IOException{ 
		SocketChannel sc=SocketChannel.open();
		sc.configureBlocking(true);
		sc.connect(inAddress);
		return sc;
	}
	
	
}
